<?php
/**
 * 消息绑定
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
use Shopnc\Tpl;


defined('InShopNC') or exit('Access Invalid!');

class message_bindControl extends BaseMemberControl
{
    public function __construct(){
        Tpl::setLayout('msg_layout');
    }

    /**
     * [wechatOp wechat 绑定]
     * @return 
     */
    public function wechatOp()
    {
        //开启 session 
        session_start();
        $logic_wx_api = Logic('wx_api');
        $model_member = Model('member');

        if(!empty($_GET['code'])) {
            // 从session中获取会员id
            $member_id = isset($_SESSION['bind_member_id']) ? (int)$_SESSION['bind_member_id'] : 0;
            if (empty($member_id)) showDialog('会员id丢失！', '', 'error', '', 3);
            $code = $_GET['code'];
            $openid = $logic_wx_api->getWxUserOpenid($code);

            if(!empty($openid)){
                // 判断用户是否关注
                $wx_info = $logic_wx_api->getWxUserInfo($openid);
                if (!isset($wx_info['subscribe']) || ($wx_info['subscribe'] !== 1)) showDialog('抱歉，请先关注公众号，<a href="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzUyMDc3Nzg1OA==&scene=124#wechat_redirect" style="color: #f32613;">点击关注公众号</a>，取消请点击返回！', '', 'error', '', 5);
                $member = $model_member->getMemberInfo(array('weixin_mp_openid'=> $openid), 'member_id,member_name');
                if (!empty($member)) showDialog('当前微信已经绑定会员' . $member['member_name'] . '，请先解绑当前绑定用户。', '', 'error', '', 3);
                
                // 将该微信的openid绑定到该用户
                $model_member->editMember(array('member_id'=> $member_id),array('weixin_mp_openid'=> $openid));
                showDialog('微信绑定成功！', '', 'succ', '', 3);

            } else {
                showDialog('微信授权失败！', '', 'error', '', 3);
            }

        } else {
            // 是否存在会员id member_id
            $member_id = isset($_GET['member_id']) ? decrypt($_GET['member_id'], 'zJsY_38rRvtTjG5') : 0;
            if (empty($member_id)) showDialog('非法的链接！', '', 'error', '', 3);
            // 是否存在该会员
            $member_exits = $model_member->getMemberInfoByID($member_id, 'member_id');
            if (!isset($member_exits['member_id']) || empty($member_exits['member_id'])) showDialog('违法的链接！', '', 'error', '', 3);
            // 保存 bind_member_id
            $_SESSION['bind_member_id'] = $member_exits['member_id'];

            $_url = $logic_wx_api->getWxOAuth2UrlBase();
            @header("location: ".$_url);
        }
    }

}
